<?php
require_once('functions.php');

function getPurchases()
{
	$conn = getConnection();
	return $conn->query('SELECT * FROM Purchase');
}

function getPurchase($id, $purchase_ID)
{ 
		$conn = getConnection();
        $results = $conn->query("SELECT * FROM Purchase WHERE user_ID=$id AND purchase_ID=$purchase_ID");
        $row = $results->fetch_assoc();
        $conn->close();
        return $row;
}

function blankPurchase($id)
{
	return array('user_ID' => $id, 'purchase_ID' => null, 'purchaseDate' => null, 'total' => null, 'creditCard' => null);
} 

function noPuchase()
{
	$conn = getConnection();
	$sql = "SELECT u.user_ID, firstName, secondName FROM User u LEFT JOIN Purchase p ON u.user_ID = p.user_ID WHERE p.user_ID IS NULL";
	$results = $conn->query($sql);
    $conn->close();
       
    return $results;
}
function deletePurchase($id, $purchase_ID)
{
		$conn = getConnection();
		$conn->query("DELETE FROM Purchase WHERE user_ID ='$id' AND purchase_ID=$purchase_ID");
		$conn->close();
		header('Location: index.php');
}
		
function savePurchase(&$row)
{
        $conn = getConnection();
        $row2 = escapeRow($row, $conn);
        
        if(!empty($row['purchase_ID']))
        	$sql =  "UPDATE Purchase SET purchaseDate='$row2[purchaseDate]', total='$row2[total]', creditCard='$row2[creditCard]' WHERE purchase_ID='$row2[purchase_ID]'";
        else
        	 $sql =  "INSERT INTO Purchase VALUES ('$row2[user_ID]', NULL, '$row2[purchaseDate]', '$row2[total]', '$row2[creditCard]')";

        $results = $conn->query($sql);
        $error = $conn->error;
        
        if(empty($row['purchase_ID']) && empty($error))
        {
                $row['purchase_ID'] = $conn->insert_id;
        }
        
        $conn->close();
       
        return $error == '' ? true : array('SQL Error' => $error);
}

